<html>
<head>
<style type="text/css">

table{	
border-collapse:collapse;	
}
tr.tables
{
border:1px solid darkgrey;
background-color:black;
color:white;
}

tr.attributes
{
border:1px solid white;
background-color:#303030;
color:white;
}
tr.rowa
{
border:1px solid white;
background-color:#D0D0D0;
color:black;
}
tr.rowb
{
border:1px solid white;
background-color:white;
color:black;
}
</style>
</head>
<body onload="updateTextboxes('actors')">

<?php
$id=$_GET["id"];

print "<div align=center><form action=search.php method=post>";
print "<input type=text maxlength=100 name=query size='150' value=\"". htmlspecialchars($raw_query)."\"></input>";
print "<input type=submit  value=Run></input></form><br>";

//SOuRCE FOR LINKS HERE
print "<div align=center><table width=800>
		<tr class=rowb>
		<td><a href=addmovie.php><b>Add Movie</b></a></td>
		<td><a href=addmovieactor.php><b>Add Movie Actor</b></a></td>
		<td><a href=addmoviedirector.php><b>Add Movie Director</b></a></td>
		<td><a href=add_actor_director.php><b>Add Actor or Director</b></a>	</td>
		</tr>
		</table></div>";

print "<script type=text/javascript>

var roles = {};

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\"/g, '&quot;').replace(/\'/g, '&#39');
}


";
if(isset($_POST["actors"])){
	for($i=0; $i < sizeof($_POST["actors"]); $i++){
		$actid="r_".$_POST["actors"][$i];
		if(isset($_POST[$actid])){
			$actrole=$_POST[$actid];
			print "roles['$actid']=\"".addslashes($actrole)."\";";
		}
	}

}

print "

function updateTextboxes(listname){
	var list = document.getElementById(listname);
	var i;
	document.getElementById('roletable').innerHTML = '';
	for( i =0; i < list.options.length; i++){
		if(list.options[i].selected){
			var textid='r_' + list.options[i].value;
			
			var textbox_input = '<input type=text onkeyup=editTextbox(\''+
								textid +'\') maxlength=50 id=' 
								+textid +' name='+ textid + ' ';
								
			if(roles[textid] != null){
				textbox_input += 'value = \'' + htmlEntities(roles[textid]) +'\' ';
			}					 
			else 
				textbox_input += 'value = \"\" ';
				
			textbox_input +='></input>';
			
			document.getElementById('roletable').innerHTML += '<tr><td><b>'+list.options[i].text + '</b></td> ' + 
															'<td>'+ textbox_input + '</td></tr>';
		}
	}
}
function editTextbox(idname){
		roles[idname] = document.getElementById(idname).value;
}

redirectTime =2500;
redirectURL = '';
function timedRedirect(url) {
	redirectURL = url;
	setTimeout('location.href = redirectURL;',redirectTime);
}

</script>"; 
		
function connect_to_server(){
	$DB="CS143";
	$db_connection = mysql_connect("localhost", "cs143", "");
	if(!$db_connection) {
		$errmsg = mysql_error($db_connection);
		print "Connection failed: " .$errmsg ."<br />";
		exit(1);
	}
	mysql_select_db("$DB", $db_connection);
	return $db_connection;

}

function make_query($command, $db_connection){
		
	$resTable = mysql_query($command, $db_connection);
	if(!$resTable) {
		$errmsg = mysql_error($db_connection);

		if($command != ""){
			print "Query fetch failed: " .$errmsg ."<br />";
		}

		exit(1);
	
	}
	return $resTable;
	
}

$data["title"] = $_POST["title"];
$data["year"] = $_POST["year"];
$data["rating"] = $_POST["rating"];
$data["company"] = $_POST["company"];
$data["actors"] = $_POST["actors"];
$data["directors"] = $_POST["directors"];
$data["genres"] = $_POST["genres"];

$conn=connect_to_server();
$getDirectorsQuery = "SELECT first,last,id FROM Director;";
$getActorsQuery = "SELECT first,last,id FROM Actor;";
$getGenresQuery = "SELECT DISTINCT genre FROM MovieGenre ;";


$res=make_query($getDirectorsQuery, $conn);
$i=0;
while($row =  mysql_fetch_row($res)){
	$form["directors"][$i]["name"] = $row[0] . " " .$row[1];
	$form["directors"][$i]["id"] = $row[2];
	$form["directors"][$i]["selected"]=false;
	if($data["directors"]!=null){
		for($j=0; $j < sizeof($data["directors"]); $j++){
			if($row[2] == $data["directors"][$j]){
				$form["directors"][$i]["selected"]=true;
				$data["directors_details"][$j]["name"] = $form["directors"][$i]["name"];
			}
		}
	}
	$i++;
}


$res=make_query($getActorsQuery, $conn);
$i=0;

while($row =  mysql_fetch_row($res)){
	$form["actors"][$i]["name"] = $row[0] . " " .$row[1];
	$form["actors"][$i]["id"] = $row[2];
	$form["actors"][$i]["selected"]=false;
	if($data["actors"]!=null){
		for($j=0; $j < sizeof($data["actors"]); $j++){
			if($row[2] == $data["actors"][$j]){
				$form["actors"][$i]["selected"]=true;
				$myid=$data["actors"][$j];
				$data["actors_details"][$j]["name"] = $form["actors"][$i]["name"];
				$data["actors_details"][$j]["id"]=$myid;
				$data["actors_details"][$j]["role"] = $_POST["r_".$data["actors"][$j]];
				
			}
		}
	}
	
	$i++;
}


$res=make_query($getGenresQuery, $conn);
$i=0;

$error=false;
while($row =  mysql_fetch_row($res)){
	$form["genres"][$i]["name"] = $row[0];
	$form["genres"][$i]["selected"]=false;
	if($data["genres"]!=null){
		for($j=0; $j < sizeof($data["genres"]); $j++){
			if($row[0] == $data["genres"][$j]){
				$form["genres"][$i]["selected"]=true;
			}
		}
	}
	$i++;
}

$ratings=array("G","PG","PG-13","R","NC-17");


print "	<h3>Add a Movie</h3>
		<form action=addmovie.php method=post>
		<table>
		<tr><td>Title </td><td><input type=text name=title value=\"". 
		htmlspecialchars($data["title"]).
		"\" maxlength=100></input>";
		
		if($data["title"] == null && isset($_POST[AddMovie])){
			print "<font color=red>Error: Title cannot be null.</font>";
			$error=true;
		}
		print "</td><tr>
		<tr><td>Year</td><td> <select name=year value=\"".$data["year"]."\">";
		$MAX_YEAR = date( 'Y',  time()) + 10;
		print "<option value=Year>Year</option>";
		for($i=1894; $i < $MAX_YEAR; $i++){
			if($data["year"] == $i)
				print "<option selected=true value=$i>$i</option>";
			else
				print "<option value=$i>$i</option>";
		}
		
		print "</select>";
		if($data["year"] == "Year"){
			print "<font color=red>Error: Year must be a value.</font>";
			$error=true;
		}
		print "</td><tr>
		<tr><td>Rating</td><td> <select name=rating >";
		for($i=0; $i < sizeof($ratings); $i++){
				print "<option value=\"" . $ratings[$i];
				if($data["rating"] == $ratings[$i])
					print "\" selected=true >";
				else
					print "\" >";
				print $ratings[$i] ."</option>";
		}
		print "</select>";
		
		print "</td><tr>
		<tr><td>Company</td><td> <input type=text name=company value=\"". 
		htmlspecialchars($data["company"])."\" maxlength=50></input>";
		
		print"</td><tr>
		</table>
		<br>
		<br>
		<table>
		<tr>
		<td><b>Choose Genres</b></td>
		<td><b>Choose Directors</b></td>
		<td><b>Choose Actors</b></td>
		</tr>
		<tr>
		<td>
		<select name='genres[]' multiple=true size=10>";
		for($i =0; $i < count($form["genres"]); $i++){
			if($form["genres"][$i]["selected"]==false)
				print "<option value=".$form["genres"][$i]["name"].">".$form["genres"][$i]["name"]."</option>";
			else
				print "<option selected=true value=\"".$form["genres"][$i]["name"]."\">".$form["genres"][$i]["name"]."</option>";
		}
		print "</select>
		</td>
		<td>
		<select name='directors[]' multiple=true size=10>

		";
		 
		for($i =0; $i < count($form["directors"]); $i++){
			if($form["directors"][$i]["selected"]==false)
				print "<option value=".$form["directors"][$i]["id"].">".$form["directors"][$i]["name"]."</option>";
			else
				print "<option selected=true value=\"".$form["directors"][$i]["id"]."\">".$form["directors"][$i]["name"]."</option>";
		}
		
		print "
		</select></td>
		
		<td>
		<select onchange=\"updateTextboxes('actors')\" id='actors' name='actors[]' multiple=true size=10>";
		for($i =0; $i < sizeof($form["actors"]); $i++){
			if($form["actors"][$i]["selected"]==true)
					print "<option  selected=true value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
			else
					print "<option value=\"".$form["actors"][$i]["id"]."\">".$form["actors"][$i]["name"]."</option>";
		}
		print "
		</select><br>
		</td>
		<td>
		<table id=roletable>
		";
		
		print "
		</table>
		</td>
		</tr>
		<tr>
		<td></td>
		<td></td>
		</tr>
		</table>
		<input type=submit  name=AddMovie value='Add Movie'></input></form><br>
		</form>
		";


		if(isset($_POST["AddMovie"])){
			if($error ==false){
				$title_unesc=$data[title];
				$company_unesc=$data[company];
				$data[title]= mysql_real_escape_string($data[title], $conn);
				$data[company]= mysql_real_escape_string($data[company], $conn);
				
				$query = "INSERT INTO Movie (title,year,rating,company) VALUES(\""
						.$data[title]."\",".$data[year].",\"".$data[rating]."\",\"".$data[company]."\")";
				make_query($query, $conn);
				
				
				$getidquery = "SELECT id FROM MaxMovieID";
				$res=make_query($getidquery, $conn);
				$row=mysql_fetch_row($res);
				$data["id"]=$row[0];
				print "<br><div align=left>
				<input value='Go To Movie' type=button onclick='window.location=\"movie?id=$data[id]\"'></input><br></div>";
				
				print "<font color=green>Added movie <b>$title_unesc ($data[year])</b>
						Rating:  <i>$data[rating]</i>, from Company <b>$company_unesc</b><br></font>";
				
				
				for($i=0; $i < sizeof($data["actors"]); $i++){
					$role_unesc = $data["actors_details"][$i]["role"];
					$role= mysql_real_escape_string($role_unesc, $conn);
					if($role != null){
						$query = "INSERT INTO MovieActor (mid, aid, role) VALUES(".
						$data["id"].",".$data["actors_details"][$i]["id"].",\"".$role
						."\")";
						make_query($query, $conn);
						print "<font color=green>Added Actor <b>".$data[actors_details][$i][name]."</b> As <b>$role_unesc</b><br> </font>";
					}
					else
						print "<font color=red>Failed to Add Actor <b>".$data[actors_details][$i][name]."</b> : Role is empty.</b><br> </font>";
					
				}
				
				for($i=0; $i < sizeof($data["directors"]); $i++){
					$query = "INSERT INTO MovieDirector (mid, did) VALUES(".
					$data[id].",".$data["directors"][$i].")";
					make_query($query, $conn);
					print "<font color=green>Added Director <b>".$data[directors_details][$i][name]."</b><br> </font>";
					
				}
				for($i=0; $i < sizeof($data["genres"]); $i++){
					$query = "INSERT INTO MovieGenre (mid, genre) VALUES(".
					$data[id].",\"".$data["genres"][$i]."\")";
					make_query($query, $conn);
					print "<font color=green>Added Genre <b>".$data[genres][$i]."</b><br> </font>";
				}
				
			}
			else{
				print "There was an error in the form. Please fix the error.<br>";
				
			}
			print "</div>";
		}
		






?>

<br>
</body>
</html>

